"use strict"

/**
 * 水印类
 */
class LBPWatermark {

  // 构造函数
  constructor(inputText, options = {}) {
    //默认设置
    this.defaultSettings = {
      disableLowBrowser: false,
      // element: "body",    // 挂载元素的id
      x: 10,              // 水印起始位置x轴坐标
      y: 150,              // 水印起始位置Y轴坐标
      rows: 2000,         // 水印行数
      cols: 2000,         // 水印列数
      xSpace: 50,         // 水印x轴间隔
      yYpace: 120,        // 水印y轴间隔
      color: '#999',      // 水印字体颜色
      opacity: 0.1,         // 水印透明度
      fontSize: '14px',   // 水印字体大小
      font: 'Microsoft Yahei',  // 水印字体
      width: 210,         // 水印宽度
      height: 30,         // 水印长度
      angle: 35,          // 水印倾斜度数
    };
    //采用配置项替换默认值，作用类似jquery.extend
    if (typeof options === "object") {
      for (let key in options) {
        if (options[key] && this.defaultSettings[key] && options[key] === this.defaultSettings[key])
          continue;
        else if (options[key])
        	console.log(options[key]);
          this.defaultSettings[key] = options[key];
          console.log(key+': '+ this.defaultSettings[key]);
      }
    }
    console.log('yYpace1: '+ this.defaultSettings['yYpace']);
    let d = new Date();
    let year = d.getFullYear();
    let month = d.getMonth() + 1;
    if (month <= 9) {
      month = '0' + month;
    }
    let day = d.getDate();
    if (day <= 9) {
      day = '0' + day;
    }
    this.inputText = inputText + '-' + year + month + day;

    // this.maskDiv = null;
    // this.mountElement = null;
    this.guid = '_coaWaterMark';
    this.total = 0;
    this.observer = null;
    this.resizeTimer = null;
    this.monitorTimer = null;

    // resize事件
    window.addEventListener('resize', () => {
      if (!this.resizeTimer) {
        this.resizeTimer = setTimeout(() => {
          this.resizeTimer = null;
          this.rebuild();
        }, 400);
      }
    });
  }

  // 初始化
  init() {
    // 判断浏览器兼容
    if (this.isIE10()) {
      if (this.defaultSettings.disableLowBrowser) {
        document.write('<div style="text-align: center;font-size: 16px;padding-top: 50px;">您的浏览器版本过低，请及时升级！</div>');
      }
      console.warn('您的浏览器版本过低，请及时升级！');
      return false;
    }
    console.log('yYpace2: '+ this.defaultSettings['yYpace']);
    var oTemp = document.createDocumentFragment();
    // var maskElement = document.getElementById(this.defaultSettings.element) || document.body;
    var maskElement = document.body;

    //获取页面最大宽度、高度
    var page_width = Math.max(maskElement.scrollWidth, maskElement.clientWidth);
    var page_height = Math.max(maskElement.scrollHeight, maskElement.clientHeight);

    //水印数量自适应元素区域尺寸
    this.defaultSettings.cols = Math.ceil(page_width / (this.defaultSettings.xSpace + this.defaultSettings.width));
    this.defaultSettings.rows = Math.ceil(page_height / (this.defaultSettings.yYpace + this.defaultSettings.height));
    console.log('yYpace:'+this.defaultSettings.yYpace+' defaultSettings.height:' + this.defaultSettings.height+' page_height:'+page_height+ ' rows: '+ this.defaultSettings.rows);
    var x;
    var y;
    for (var i = 0; i < this.defaultSettings.rows; i++) {
      y = this.defaultSettings.y + (this.defaultSettings.yYpace + this.defaultSettings.height) * i;
      for (var j = 0; j < this.defaultSettings.cols; j++) {
        x = this.defaultSettings.x + (this.defaultSettings.width + this.defaultSettings.xSpace) * j;
        var mask_div = document.createElement('div');
        mask_div.id = this.guid + i + j;
        mask_div.className = this.guid;
        //mask_div.appendChild(document.createTextNode(this.defaultSettings.txt));
        mask_div.innerHTML = (this.inputText);
        //设置水印div倾斜显示
        mask_div.style.webkitTransform = "rotate(-" + this.defaultSettings.angle + "deg)";
        mask_div.style.MozTransform = "rotate(-" + this.defaultSettings.angle + "deg)";
        mask_div.style.msTransform = "rotate(-" + this.defaultSettings.angle + "deg)";
        mask_div.style.OTransform = "rotate(-" + this.defaultSettings.angle + "deg)";
        mask_div.style.transform = "rotate(-" + this.defaultSettings.angle + "deg)";
        mask_div.style.visibility = "visible";
        mask_div.style.position = "fixed";
        mask_div.style.left = x + 'px';
        mask_div.style.top = y + 'px';
        mask_div.style.overflow = "hidden";
        mask_div.style.zIndex = "999999";
        mask_div.style.pointerEvents = 'none';//pointer-events:none  让水印不遮挡页面的点击事件
        mask_div.style.filter = "alpha(opacity=50)"; //兼容IE9以下的透明度设置
        mask_div.style.opacity = this.defaultSettings.opacity + Math.random() * 0.1;
        mask_div.style.fontSize = this.defaultSettings.fontSize;
        mask_div.style.fontFamily = this.defaultSettings.font;
        // mask_div.style.color = this.defaultSettings.color;
        let colorRandom1 = Math.ceil(Math.random() * 30) + 120;
        let colorRandom2 = Math.ceil(Math.random() * 30) + 120;
        let colorRandom3 = Math.ceil(Math.random() * 30) + 120;
        mask_div.style.color = `rgb(${colorRandom1}, ${colorRandom2}, ${colorRandom3})`;
        mask_div.style.textAlign = "center";
        mask_div.style.width = this.defaultSettings.width + 'px';
        // if (j == this.defaultSettings.cols - 1) {
        // let width = page_width - x - 50;
        // width = width > 0 ? width : 0;
        // mask_div.style.width = width + 'px';
        // }
        mask_div.style.height = this.defaultSettings.height + 'px';
        mask_div.style.whiteSpace = "nowrap";
        mask_div.style.display = "block";
        // if (navigator.appName != 'Microsoft Internet Explorer') {
        //   mask_div.style.backgroundRepeat = "no-repeat";
        //   mask_div.style.backgroundImage = "url('bg.png')";
        //   mask_div.style.webkitTextFillColor = "transparent";
        //   mask_div.style.webkitBackgroundClip = "text";
        // }
        oTemp.appendChild(mask_div);

        this.total += 1;
      }
    }
    maskElement.appendChild(oTemp);
    // this.mountElement = maskElement;

    if (!this.monitorTimer) {
      this.monitorTimer = setTimeout(() => {
        this.monitorTimer = null;
        this.monitor();
      }, 2000);
    }
  }

  isIE10() {
    if (navigator.appName == 'Microsoft Internet Explorer') {
      var agent = navigator.userAgent;
      if (agent.match(/MSIE ([0-9]{1,}[\.0-9]{0,})/) != null) {
        var version = parseFloat(RegExp.$1);
        if (version < 11)
          return true;
      }
    }
    return false;
  }

  // 监控
  monitor() {
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    if (MutationObserver) {
      this.observer = new MutationObserver((mutations, observer) => {
        let first = mutations[0];

        // 当maskDiv节点被删除
        if (first.removedNodes[0]) {
          let element = first.removedNodes[0];
          if (element.className == this.guid || (element.id && element.id.indexOf(this.guid) === 0)) {
            this.rebuild();
            return false;
          }
        }

        // 水印的style被修改
        if (first.attributeName === 'style' && first.target.className == this.guid) {
          this.rebuild();
          return false;
        }

        // 禁止修改水印内容
        if (first.type == 'characterData' && first.target.parentElement.className == this.guid) {
          this.rebuild();
          return false;
        }

        // 禁止删除水印的class或id
        if (first.attributeName == 'class' || first.attributeName == 'id') {
          if (first.oldValue && first.oldValue.indexOf(this.guid) === 0) {
            this.rebuild();
            return false;
          }
        }

        // 判断水印块数量对不对
        if (document.getElementsByClassName(this.guid).length != this.total) {
          this.rebuild();
          return false;
        }

        // 禁止其他元素的zindex大于999999
        if (first.target.style && first.target.style.zIndex >= 999999 && first.target.className !== this.guid) {
          first.target.style.zIndex = 999998;
          return false;
        }
      });

      var body = document.getElementsByTagName('body')[0];
      this.observer.observe(body, {
        childList: true,
        attributes: true,
        attributeOldValue: true,
        subtree: true,
        characterData: true,
        characterDataOldValue: true,
      });
    } else {
      console.warn('您的浏览器版本过低，请及时升级！');
    }
  }

  // 重建索引
  rebuild() {
    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }

    document.querySelectorAll(`[id^=${this.guid}], [class^=${this.guid}], [class*=${this.guid}]`).forEach(item => {
      document.body.removeChild(item);
    })

    this.init();
  }
}

